package com.demo.blog;

import java.io.ByteArrayInputStream;

import org.apache.log4j.Logger;

import com.baidu.bae.api.util.BaeEnv;
import com.demo.kit.ImageKit;
import com.demo.util.BCSUtils;
import com.demo.util.HtmlFilter;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

/**
 * BlogController
 * 注意：在实际项目中业务与sql需要写在Model中，此demo仅为示意,故将sql写在了Controller中
 */
@Before(BlogInterceptor.class)
public class BlogController extends Controller {
	
	private static final Logger log = Logger.getLogger(BlogController.class);
	private static final String IMG_TYPE = ".jpg|.jepg|.gif|.png|.bmp";
	
	public void index() {
		setAttr("blogPage", Blog.dao.paginate(getParaToInt(0, 1), 10, "select *", "from blog order by id asc"));
		render("blog.html");
	}
	
	public void add() {
	}
	
	@Before(BlogValidator.class)
	public void save() {
	    String title = getPara("blog.title");
        String content = getPara("blog.content");
        new Blog().set("title", HtmlFilter.getText(title)).set("content", HtmlFilter.getBasicHtmlandimage(content)).save();
		redirect("/blog");
	}
	
	public void edit() {
		setAttr("blog", Blog.dao.findById(getParaToInt()));
	}
	
	@Before(BlogValidator.class)
	public void update() {
		getModel(Blog.class).update();
		redirect("/blog");
	}
	
	public void delete() {
		Blog.dao.deleteById(getParaToInt());
		redirect("/blog");
	}
	
	public void editor(){
		String tmpfsPath = BaeEnv.getTmpfsPath();
        try {
        	UploadFile file = getFile("imgFile", tmpfsPath, 1024 * 1024);
            String oldName = file.getFileName();
        	String fileType = oldName.substring(oldName.lastIndexOf("."), oldName.length());
        	if(IMG_TYPE.indexOf(fileType.toLowerCase()) == -1){
        		 setAttr("error", 1);
                 setAttr("message", "上传出错，请检查图片格式！");
                 render(new JsonRender(new String[]{"error", "message"}).forIE());
                 return;
        	}
            String newName = System.currentTimeMillis() + fileType;
            // 第一次上传文件
            BCSUtils.uploadByFile(file.getFile(), newName);
            String url = "http://bcs.duapp.com/" + BCSUtils.bucket + "/" + newName;
            byte[] bs = ImageKit.watermark(url, "dreamlu.net");
            // 第二次水印之后重新上传
            BCSUtils.uploadByInputStream(new ByteArrayInputStream(bs), "image/jpeg", bs.length, newName);
            setAttr("error", 0);
            setAttr("url", url);
            render(new JsonRender(new String[]{"error", "url"}).forIE());
        } catch (Exception e) {
            log.error(e);
            setAttr("error", 1);
            setAttr("message", "上传出错，请稍候再试！");
            render(new JsonRender(new String[]{"error", "message"}).forIE());
        }
	}
}


